package com.example.cinemasystemv2.controller;

import com.example.cinemasystemv2.entity.*;
import com.example.cinemasystemv2.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import jakarta.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Controller
@RequestMapping("/admin")
public class AdminController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private MovieService movieService;
    
    @Autowired
    private ScreeningService screeningService;
    
    @Autowired
    private ScreeningRoomService screeningRoomService;
    
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private SystemLogService systemLogService;
    
    // 检查管理员权限
    private boolean checkAdminRole(HttpSession session) {
        String role = (String) session.getAttribute("role");
        return "admin".equals(role);
    }
    
    private void addCurrentUserToModel(Model model, HttpSession session) {
        String username = (String) session.getAttribute("username");
        User currentUser = userService.getUserByUsername(username).orElse(null);
        model.addAttribute("currentUser", currentUser);
    }
    
    // 用户管理
    @GetMapping("/users")
    public String userManagement(Model model, HttpSession session) {
        try {
            if (!checkAdminRole(session)) {
                return "redirect:/";
            }
            
            addCurrentUserToModel(model, session);
            
            List<User> allUsers = userService.getAllUsers();
            long adminCount = userService.countUsersByRole("admin");
            long managerCount = userService.countUsersByRole("manager");
            long receptionistCount = userService.countUsersByRole("receptionist");
            
            model.addAttribute("users", allUsers);
            model.addAttribute("totalUsers", allUsers.size());
            model.addAttribute("adminUsers", adminCount);
            model.addAttribute("managerUsers", managerCount);
            model.addAttribute("receptionistUsers", receptionistCount);
            return "admin/users";
        } catch (Exception e) {
            systemLogService.log("用户管理页面访问失败: " + e.getMessage(), "admin", "ERROR");
            model.addAttribute("error", "加载用户数据失败: " + e.getMessage());
            return "error";
        }
    }
    
    @PostMapping("/users/create")
    public String createUser(@RequestParam String username,
                            @RequestParam String password,
                            @RequestParam String role,
                            @RequestParam String phoneNumber,
                            HttpSession session,
                            RedirectAttributes redirectAttributes) {
        if (!checkAdminRole(session)) {
            return "redirect:/";
        }
        
        try {
            userService.createUser(username, password, role, phoneNumber);
            redirectAttributes.addFlashAttribute("success", "用户创建成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "创建失败: " + e.getMessage());
        }
        
        return "redirect:/admin/users";
    }
    
    /*@PostMapping("/users/delete/{userId}")
    public String deleteUser(@PathVariable Long userId,
                           HttpSession session,
                           RedirectAttributes redirectAttributes) {
        if (!checkAdminRole(session)) {
            return "redirect:/login";
        }
        
        try {
            userService.deleteUser(userId);
            redirectAttributes.addFlashAttribute("success", "用户删除成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "删除用户失败: " + e.getMessage());
        }
        
        return "redirect:/admin/users";
    }
    */
    
    // 处理前端JavaScript调用的删除用户请求
    @PostMapping("/users/delete")
    public String deleteUserByForm(@RequestParam Long userId,
                                  HttpSession session,
                                  RedirectAttributes redirectAttributes) {
        if (!checkAdminRole(session)) {
            return "redirect:/login";
        }
        
        try {
            userService.deleteUser(userId);
            redirectAttributes.addFlashAttribute("successMessage", "用户删除成功！");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "删除用户失败: " + e.getMessage());
        }
        
        return "redirect:/admin/users";
    }
    

    
    // 编辑用户页面
    @GetMapping("/users/edit/{userId}")
    public String editUserPage(@PathVariable Long userId, Model model, HttpSession session) {
        if (!checkAdminRole(session)) {
            return "redirect:/login";
        }
        
        addCurrentUserToModel(model, session);
        
        Optional<User> userOpt = userService.getUserById(userId);
        if (userOpt.isPresent()) {
            model.addAttribute("user", userOpt.get());
            return "admin/edit-user";
        } else {
            return "redirect:/admin/users";
        }
    }
    
    // 更新用户信息
    @PostMapping("/users/edit")
    public String updateUser(@RequestParam Long userId,
                            @RequestParam String username,
                            @RequestParam String phoneNumber,
                            @RequestParam String role,
                            @RequestParam(required = false) Boolean mustChangePassword,
                            HttpSession session,
                            RedirectAttributes redirectAttributes) {
        if (!checkAdminRole(session)) {
            return "redirect:/login";
        }
        
        try {
            Optional<User> userOpt = userService.getUserById(userId);
            if (userOpt.isPresent()) {
                User user = userOpt.get();
                user.setPhoneNumber(phoneNumber);
                user.setRole(role);
                user.setMustChangePassword(mustChangePassword != null ? mustChangePassword : false);
                userService.updateUser(user);
                redirectAttributes.addFlashAttribute("successMessage", "用户信息更新成功！");
            } else {
                redirectAttributes.addFlashAttribute("errorMessage", "用户不存在");
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "更新用户失败: " + e.getMessage());
        }
        
        return "redirect:/admin/users";
    }

    @PostMapping("/users/reset-password/{userId}")
    public String resetPassword(@PathVariable Long userId,
                              HttpSession session,
                              RedirectAttributes redirectAttributes) {
        if (!checkAdminRole(session)) {
            return "redirect:/login";
        }
        
        try {
            Optional<User> userOpt = userService.getUserById(userId);
            if (userOpt.isPresent()) {
                User user = userOpt.get();
                userService.resetPassword(userId);
                String adminUsername = (String) session.getAttribute("username");
                systemLogService.log("重置" + user.getRole() + user.getUsername() + "的密码", adminUsername, "RESET_PASSWORD");
                redirectAttributes.addFlashAttribute("success", "密码重置成功，新密码为：123456");
            } else {
                redirectAttributes.addFlashAttribute("error", "用户不存在");
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "重置密码失败: " + e.getMessage());
        }
        
        return "redirect:/admin/users";
    }
    
    // 重置用户密码（编辑页面表单提交）
    @PostMapping("/users/reset-password")
    public String resetPasswordFromEdit(@RequestParam Long userId,
                                       HttpSession session,
                                       RedirectAttributes redirectAttributes) {
        if (!checkAdminRole(session)) {
            return "redirect:/login";
        }
        
        try {
            Optional<User> userOpt = userService.getUserById(userId);
            if (userOpt.isPresent()) {
                User user = userOpt.get();
                if ("admin".equals(user.getRole())) {
                    redirectAttributes.addFlashAttribute("errorMessage", "不能重置管理员密码");
                } else {
                    userService.resetPassword(userId);
                    String adminUsername = (String) session.getAttribute("username");
                    systemLogService.log("重置" + user.getRole() + user.getUsername() + "的密码", adminUsername, "RESET_PASSWORD");
                    redirectAttributes.addFlashAttribute("successMessage", "密码重置成功，新密码为：123456");
                }
            } else {
                redirectAttributes.addFlashAttribute("errorMessage", "用户不存在");
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "重置密码失败: " + e.getMessage());
        }
        
        return "redirect:/admin/users/edit/" + userId;
    }
    
    // 管理员修改自身密码（AJAX）
    @PostMapping("/change-password")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> changePassword(
            @RequestParam String currentPassword,
            @RequestParam String newPassword,
            HttpSession session) {
        
        Map<String, Object> response = new HashMap<>();
        
        if (!checkAdminRole(session)) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.ok(response);
        }
        
        String username = (String) session.getAttribute("username");
        
        if (!userService.verifyPassword(username, currentPassword)) {
            response.put("success", false);
            response.put("message", "当前密码错误");
            return ResponseEntity.ok(response);
        }
        
        userService.updatePassword(username, newPassword);
        systemLogService.log("修改管理员密码", username, "CHANGE_ADMIN_PASSWORD");
        
        response.put("success", true);
        response.put("message", "密码修改成功");
        
        return ResponseEntity.ok(response);
    }
    
    // 重置非管理员用户密码（AJAX）
    @PostMapping("/reset-user-password")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> resetUserPassword(
            @RequestParam String username,
            HttpSession session) {
        
        Map<String, Object> response = new HashMap<>();
        
        if (!checkAdminRole(session)) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.ok(response);
        }
        
        Optional<User> targetUserOpt = userService.getUserByUsername(username);
        
        if (!targetUserOpt.isPresent()) {
            response.put("success", false);
            response.put("message", "用户不存在");
            return ResponseEntity.ok(response);
        }
        
        User targetUser = targetUserOpt.get();
        if ("admin".equals(targetUser.getRole())) {
            response.put("success", false);
            response.put("message", "不能重置管理员密码");
            return ResponseEntity.ok(response);
        }
        
        // 重置密码为123456
        userService.updatePassword(username, "123456");
        userService.setPasswordChangeRequired(username, true);
        
        // 记录日志
        String adminUsername = (String) session.getAttribute("username");
        String logMessage = String.format("重置%s%s的密码", targetUser.getRole(), username);
        systemLogService.log(logMessage, adminUsername, "RESET_PASSWORD");
        
        response.put("success", true);
        response.put("message", "密码重置成功，新密码为：123456");
        
        return ResponseEntity.ok(response);
    }
    
    
    // 获取场次的座位信息
    @GetMapping("/screenings/{screeningId}/seats")
    @ResponseBody
    public java.util.Map<String, Object> getScreeningSeats(@PathVariable Long screeningId, HttpSession session) {
        java.util.Map<String, Object> response = new java.util.HashMap<>();
        
        try {
            Optional<Screening> screeningOpt = screeningService.getScreeningById(screeningId);
            if (screeningOpt.isPresent()) {
                Screening screening = screeningOpt.get();
                ScreeningRoom room = screening.getRoom();
                
                // 获取已售座位
                List<String> occupiedSeats = orderService.getOccupiedSeatsByScreening(screeningId);
                
                response.put("success", true);
                response.put("rows", room.getNumRows());
                response.put("seatsPerRow", room.getSeatsPerRow());
                response.put("occupiedSeats", occupiedSeats);
            } else {
                response.put("success", false);
                response.put("message", "场次不存在");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取座位信息失败: " + e.getMessage());
        }
        
        return response;
    }
    
    // 放映厅管理
    @GetMapping("/rooms")
    public String roomManagement(Model model, HttpSession session) {
        if (!checkAdminRole(session)) {
            return "redirect:/";
        }
        
        addCurrentUserToModel(model, session);
        model.addAttribute("rooms", screeningRoomService.getAllRooms());
        return "admin/rooms";
    }
    
    @PostMapping("/rooms/create")
    public String createRoom(@RequestParam String name,
                            @RequestParam int seatCount,
                            @RequestParam(required = false) String roomType,
                            @RequestParam(required = false) String equipment,
                            @RequestParam(required = false) String description,
                            HttpSession session,
                            RedirectAttributes redirectAttributes) {
        if (!checkAdminRole(session)) {
            return "redirect:/";
        }
        
        try {
            // 根据座位总数计算合理的行数和每行座位数
            int rows = (int) Math.ceil(Math.sqrt(seatCount));
            int seatsPerRow = (int) Math.ceil((double) seatCount / rows);
            
            ScreeningRoom room = new ScreeningRoom(name, rows, seatsPerRow);
            room.setSeatCount(seatCount); // 直接设置用户输入的座位数
            room.setRoomType(roomType);
            room.setEquipment(equipment);
            room.setDescription(description);
            
            screeningRoomService.saveRoom(room);
            redirectAttributes.addFlashAttribute("success", "放映厅创建成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "创建失败: " + e.getMessage());
        }
        
        return "redirect:/admin/rooms";
    }
    
                                                                                                                                                                                                                                                                                                         // 获取单个放映厅信息
    @GetMapping("/rooms/get/{id}")
    @ResponseBody
    public java.util.Map<String, Object> getRoom(@PathVariable Long id, HttpSession session) {
        java.util.Map<String, Object> response = new java.util.HashMap<>();
        
        if (!checkAdminRole(session)) {
            response.put("success", false);
            response.put("message", "权限不足");
            return response;
        }
        
        try {
            Optional<ScreeningRoom> roomOpt = screeningRoomService.getRoomById(id);
            if (roomOpt.isPresent()) {
                ScreeningRoom room = roomOpt.get();
                response.put("success", true);
                response.put("id", room.getId());
                response.put("name", room.getName());
                response.put("seatCount", room.getTotalSeats());
                response.put("roomType", room.getRoomType());
                response.put("equipment", room.getEquipment());
                response.put("description", room.getDescription());
            } else {
                response.put("success", false);
                response.put("message", "放映厅不存在");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取放映厅信息失败：" + e.getMessage());
        }
        
        return response;
    }
    
    // 编辑放映厅
    @PostMapping("/rooms/edit")
    public String editRoom(@RequestParam Long roomId,
                          @RequestParam String name,
                          @RequestParam int seatCount,
                          @RequestParam(required = false) String roomType,
                          @RequestParam(required = false) String equipment,
                          @RequestParam(required = false) String description,
                          HttpSession session,
                          RedirectAttributes redirectAttributes) {
        if (!checkAdminRole(session)) {
            return "redirect:/";
        }
        
        try {
            Optional<ScreeningRoom> roomOpt = screeningRoomService.getRoomById(roomId);
            if (roomOpt.isPresent()) {
                ScreeningRoom room = roomOpt.get();
                room.setName(name);
                
                // 根据座位总数计算合理的行数和每行座位数
                int rows = (int) Math.ceil(Math.sqrt(seatCount));
                int seatsPerRow = (int) Math.ceil((double) seatCount / rows);
                
                room.setNumRows(rows);
                room.setSeatsPerRow(seatsPerRow);
                room.setSeatCount(seatCount); // 直接设置用户输入的座位数
                room.setRoomType(roomType);
                room.setEquipment(equipment);
                room.setDescription(description);
                
                screeningRoomService.saveRoom(room);
                redirectAttributes.addFlashAttribute("successMessage", "放映厅更新成功！");
            } else {
                redirectAttributes.addFlashAttribute("errorMessage", "放映厅不存在");
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "更新放映厅失败：" + e.getMessage());
        }
        
        return "redirect:/admin/rooms";
    }
    
    // 删除放映厅
    @GetMapping("/rooms/delete/{roomId}")
    public String deleteRoom(@PathVariable Long roomId,
                            HttpSession session,
                            RedirectAttributes redirectAttributes) {
        if (!checkAdminRole(session)) {
            return "redirect:/";
        }
        
        try {
            screeningRoomService.deleteRoom(roomId);
            redirectAttributes.addFlashAttribute("successMessage", "放映厅删除成功！");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "放映厅删除失败：" + e.getMessage());
        }
        
        return "redirect:/admin/rooms";
    }
    
    // 查看放映厅场次
    @GetMapping("/room-screenings/{roomId}")
    public String roomScreenings(@PathVariable Long roomId, Model model, HttpSession session) {
        if (!checkAdminRole(session)) {
            return "redirect:/";
        }
        
        addCurrentUserToModel(model, session);
        
        try {
            // 获取放映厅信息
            Optional<ScreeningRoom> roomOpt = screeningRoomService.getRoomById(roomId);
            if (!roomOpt.isPresent()) {
                model.addAttribute("error", "放映厅不存在");
                return "admin/rooms";
            }
            
            ScreeningRoom room = roomOpt.get();
            List<Screening> screenings = screeningService.getScreeningsByRoom(room);
            
            model.addAttribute("room", room);
            model.addAttribute("screenings", screenings);
            
            return "admin/room-screenings"; // 临时使用简单测试页面
        } catch (Exception e) {
            e.printStackTrace(); // 打印完整的异常堆栈
            System.err.println("AdminController.roomScreenings异常: " + e.getMessage());
            model.addAttribute("error", "获取场次信息失败: " + e.getMessage());
            model.addAttribute("roomId", roomId);
            return "admin/room-screenings"; // 返回当前页面而不是rooms页面
        }
    }
    
    // 所有场次管理功能已移至经理模块
    
    // 所有小吃管理功能已移至经理模块
    
    // 订单管理
    @GetMapping("/orders")
    public String orderManagement(Model model, HttpSession session,
                                 @RequestParam(defaultValue = "1") int page,
                                 @RequestParam(defaultValue = "10") int size) {
        if (!checkAdminRole(session)) {
            return "redirect:/";
        }
        
        addCurrentUserToModel(model, session);
        
        // 实现真正的分页逻辑
        List<Order> allOrders = orderService.getAllOrders();
        int totalOrders = allOrders.size();
        int totalPages = (int) Math.ceil((double) totalOrders / size);
        
        // 计算分页范围
        int startIndex = (page - 1) * size;
        int endIndex = Math.min(startIndex + size, totalOrders);
        
        List<Order> pagedOrders = allOrders.subList(startIndex, endIndex);
        
        model.addAttribute("orders", pagedOrders);
        model.addAttribute("todayOrders", orderService.getTodayOrders());
        model.addAttribute("todaySales", orderService.getTotalSalesByDate(LocalDateTime.now()));
        
        // 添加分页信息
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("pageSize", size);
        model.addAttribute("totalOrders", totalOrders);
        
        return "admin/orders";
    }
    
    // 场次订单管理
    @GetMapping("/screening-orders/{screeningId}")
    public String screeningOrders(@PathVariable Long screeningId, Model model, HttpSession session) {
        if (!checkAdminRole(session)) {
            return "redirect:/";
        }
        
        addCurrentUserToModel(model, session);
        
        try {
            Optional<Screening> screeningOpt = screeningService.getScreeningById(screeningId);
            if (screeningOpt.isEmpty()) {
                return "redirect:/admin/screenings";
            }
            
            Screening screening = screeningOpt.get();
            List<Order> orders = orderService.getOrdersByScreening(screening);
        
        model.addAttribute("screening", screening);
            model.addAttribute("orders", orders);
            
            // 统计信息
            java.util.Map<String, Object> stats = new java.util.HashMap<>();
            stats.put("totalOrders", orders.size());
            stats.put("totalRevenue", orders.stream().mapToDouble(Order::getAmount).sum());
            stats.put("soldSeats", orders.size());
            stats.put("availableSeats", screening.getRoom().getTotalSeats() - orders.size());
            model.addAttribute("stats", stats);
            
            return "admin/screening-orders";
        } catch (Exception e) {
            return "redirect:/admin/screenings";
        }
    }
    
    // 订单详情
    @GetMapping("/order-detail/{orderId}")
    public String orderDetail(@PathVariable String orderId, Model model, HttpSession session) {
        if (!checkAdminRole(session)) {
            return "redirect:/";
        }
        
        addCurrentUserToModel(model, session);
        
        try {
            Optional<Order> orderOpt = orderService.getOrderById(orderId);
            if (orderOpt.isEmpty()) {
                return "redirect:/admin/orders";
            }
            
            model.addAttribute("order", orderOpt.get());
            return "admin/order-detail";
        } catch (Exception e) {
            return "redirect:/admin/orders";
        }
    }
    
    // 订单退款
    @PostMapping("/orders/refund/{orderId}")
    @ResponseBody
    public java.util.Map<String, Object> refundOrder(@PathVariable String orderId, HttpSession session) {
        java.util.Map<String, Object> response = new java.util.HashMap<>();
        
        if (!checkAdminRole(session)) {
            response.put("success", false);
            response.put("message", "权限不足");
            return response;
        }
        
        try {
            Order refundedOrder = orderService.refundOrder(orderId);
            response.put("success", true);
            response.put("message", "退款成功，退款金额: ¥" + refundedOrder.getRefundAmount());
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "退款失败: " + e.getMessage());
        }
        
        return response;
    }
    
    // 取消订单
    @PostMapping("/orders/cancel/{orderId}")
    @ResponseBody
    public java.util.Map<String, Object> cancelOrder(@PathVariable String orderId, HttpSession session) {
        java.util.Map<String, Object> response = new java.util.HashMap<>();
        
        if (!checkAdminRole(session)) {
            response.put("success", false);
            response.put("message", "权限不足");
            return response;
        }
        
        try {
            orderService.refundOrder(orderId);
            response.put("success", true);
            response.put("message", "订单已取消");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "取消失败: " + e.getMessage());
        }
        
        return response;
    }
    
    // 系统日志
    @GetMapping("/logs")
    public String systemLogs(Model model, HttpSession session,
                            @RequestParam(defaultValue = "0") int page,
                            @RequestParam(defaultValue = "20") int size,
                            @RequestParam(required = false) String date) {
        if (!checkAdminRole(session)) {
            return "redirect:/";
        }
        
        addCurrentUserToModel(model, session);
        
        // 根据是否有日期参数选择不同的查询方法
        List<SystemLog> allLogs;
        if (date != null && !date.isEmpty()) {
            allLogs = systemLogService.getLogsByDate(date);
        } else {
            allLogs = systemLogService.getAllLogs();
        }
        
        int totalLogs = allLogs.size();
        int totalPages = (int) Math.ceil((double) totalLogs / size);
        
        // 计算分页范围
        int startIndex = page * size;
        int endIndex = Math.min(startIndex + size, totalLogs);
        
        List<SystemLog> pagedLogs = allLogs.subList(startIndex, endIndex);
        
        // 计算统计数据
        LocalDateTime today = LocalDateTime.now();
        LocalDateTime startOfDay = today.toLocalDate().atStartOfDay();
        LocalDateTime endOfDay = startOfDay.plusDays(1);
        List<SystemLog> todayLogs = systemLogService.getLogsByDateRange(startOfDay, endOfDay);
        long errorLogs = allLogs.stream().filter(log -> log.getLogContent().contains("ERROR") || log.getLogContent().contains("错误")).count();
        long warningLogs = allLogs.stream().filter(log -> log.getLogContent().contains("WARNING") || log.getLogContent().contains("警告")).count();
        
        model.addAttribute("logs", pagedLogs);
        model.addAttribute("currentPage", page);
        model.addAttribute("pageSize", size);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("totalLogs", totalLogs);
        model.addAttribute("selectedDate", date);
        model.addAttribute("todayLogs", todayLogs.size());
        model.addAttribute("errorLogs", errorLogs);
        model.addAttribute("warningLogs", warningLogs);
        
        return "admin/logs";
    }
    
    // 管理员仪表板
    @GetMapping("/dashboard")
    public String dashboard(Model model, HttpSession session) {
        if (!checkAdminRole(session)) {
            return "redirect:/";
        }
        
        addCurrentUserToModel(model, session);
        
        // 添加统计数据
        model.addAttribute("userCount", userService.getAllUsers().size());
        model.addAttribute("movieCount", movieService.getAllMovies().size());
        model.addAttribute("orderCount", orderService.getAllOrders().size());
        model.addAttribute("todaySales", orderService.getTotalSalesByDate(LocalDateTime.now()));
        
        // 添加最近的日志
        List<SystemLog> recentLogs = systemLogService.getAllLogs();
        if (recentLogs.size() > 10) {
            recentLogs = recentLogs.subList(0, 10);
        }
        model.addAttribute("recentLogs", recentLogs);
        
        return "admin/dashboard";
    }
    
    // 添加用户页面
    @GetMapping("/users/add")
    public String addUserPage(Model model, HttpSession session) {
        if (!checkAdminRole(session)) {
            return "redirect:/";
        }
        
        addCurrentUserToModel(model, session);
        return "admin/add-user";
    }
    
    // 处理添加用户表单提交
    @PostMapping("/users/add")
    public String addUser(@RequestParam String username,
                         @RequestParam String password,
                         @RequestParam String phoneNumber,
                         @RequestParam String role,
                         HttpSession session,
                         RedirectAttributes redirectAttributes) {
        if (!checkAdminRole(session)) {
            return "redirect:/";
        }
        
        try {
            userService.createUser(username, password, role, phoneNumber);
            redirectAttributes.addFlashAttribute("successMessage", "用户创建成功！");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "用户创建失败：" + e.getMessage());
        }
        
        return "redirect:/admin/users";
    }
}